package craky.keeper.user;

import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dialog;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.util.ArrayList;
import java.util.List;

import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.JComponent;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import org.hibernate.criterion.Criterion;

import craky.component.CommonTableModel;
import craky.component.JImagePane;
import craky.componentc.JCButton;
import craky.componentc.JCDialog;
import craky.componentc.JCMenuItem;
import craky.componentc.JCMessageBox;
import craky.componentc.JCPopupMenu;
import craky.componentc.JCScrollTable;
import craky.componentc.JCTable;
import craky.componentc.JCTableHeader;
import craky.keeper.KeeperApp;
import craky.layout.LineLayout;
import craky.util.UIUtil;

public class UserListDialog extends JCDialog {
	private static final long serialVersionUID = 3367067393044735726L;
	private KeeperApp keeper;
	private JComponent content;
	private Action addAction;
	private Action modifyAction;
	private Action deleteAction;
	private Action cancelAction;
	private CommonTableModel<User> model;
	private JCTable table;
	private JCPopupMenu popup;
	private List<User> userList;
	private User currentUser;

	public UserListDialog(KeeperApp keeper) {
		super(keeper.getMainFrame(), "用户管理", Dialog.ModalityType.DOCUMENT_MODAL);
		this.keeper = keeper;
		initActions();
		initUI();
		load();
		setVisible(true);
	}

	private void initActions() {
		this.addAction = new AbstractAction("添加") {
			private static final long serialVersionUID = -3647919093948535545L;

			public void actionPerformed(ActionEvent e) {
				UserInfoDialog infoDialog = new UserInfoDialog(
						UserListDialog.this.keeper, UserListDialog.this, null,
						false);
				User user = infoDialog.getUser();

				if (user != null) {
					UserListDialog.this.model.insertRowData(user);
				}
			}
		};
		this.modifyAction = new AbstractAction("修改密码") {
			private static final long serialVersionUID = -1204636388592876724L;

			public void actionPerformed(ActionEvent e) {
				new UserInfoDialog(UserListDialog.this.keeper,
						UserListDialog.this,
						UserListDialog.this.currentUser.getName(), false);
			}
		};
		this.deleteAction = new AbstractAction("删除") {
			private static final long serialVersionUID = -5377194934609055107L;

			public void actionPerformed(ActionEvent e) {
				UserListDialog dialog = UserListDialog.this;
				String title = "删除用户";
				String info = "确定要删除该用户吗？";

				if (JCMessageBox.createQuestionMessageBox(dialog, title, info)
						.open() == 4) {
					info = "用户删除成功＄1�7";
					UserListDialog.this.keeper
							.removeHistoryUser(UserListDialog.this.currentUser
									.getName());
					UserDAO.deleteUser(UserListDialog.this.currentUser);
					UserListDialog.this.model
							.delRowData(UserListDialog.this.currentUser);
					JCMessageBox.createInformationMessageBox(dialog, title,
							info).open();
				}
			}
		};
		this.cancelAction = new AbstractAction("取消") {
			private static final long serialVersionUID = 7342539127081422526L;

			public void actionPerformed(ActionEvent e) {
				UserListDialog.this.dispose();
			}
		};
		this.modifyAction.setEnabled(false);
		this.deleteAction.setEnabled(false);
	}

	private void initUI() {
		String[] columnsName = { "用户各1�7", "权限" };
		@SuppressWarnings("rawtypes")
		Class[] columnsClass = { String.class, String.class };
		String[] getMethodsName = { "getName", "getPurviewName" };
		String[] setMethodsName = { "setName", "setPurviewName" };
		JImagePane buttonPane = new JImagePane();
		this.content = ((JComponent) getContentPane());
		JCButton btnAdd = new JCButton(this.addAction);
		JCButton btnModify = new JCButton(this.modifyAction);
		JCButton btnDelete = new JCButton(this.deleteAction);
		JCButton btnCancel = new JCButton(this.cancelAction);
		this.userList = new ArrayList<User>();
		JCScrollTable scTable = new JCScrollTable();
		this.table = scTable.getTable();
		JCTableHeader header = (JCTableHeader) this.table.getTableHeader();
		this.model = new CommonTableModel<User>(scTable.getTable(),
				columnsName, columnsClass, getMethodsName, setMethodsName,
				this.userList);
		this.popup = new JCPopupMenu();
		JCMenuItem miModify = new JCMenuItem(this.modifyAction);
		JCMenuItem miDelete = new JCMenuItem(this.deleteAction);

		this.content.setPreferredSize(new Dimension(400, 250));
		this.content.setBorder(new EmptyBorder(0, 2, 2, 2));
		this.content.setLayout(new BorderLayout());
		scTable.setColumnControlEnabled(false);
		header.setShowPopupMenu(false);
		header.setReorderingAllowed(false);
		header.setResizingAllowed(false);
		this.table.setModel(this.model);
		this.table.setDragEnabled(false);
		this.table.setAutoResizeMode(4);
		this.table.setSelectionMode(0);
		this.table.setAutoCreateRowSorter(true);
		buttonPane.setLayout(new LineLayout(5, 7, 7, 7, 0, 10, 10, 0));
		buttonPane.setBackground(new Color(255, 255, 255, 150));
		buttonPane.setPreferredSize(new Dimension(-1, 32));
		btnAdd.setPreferredSize(new Dimension(69, 21));
		btnModify.setPreferredSize(btnAdd.getPreferredSize());
		btnDelete.setPreferredSize(btnAdd.getPreferredSize());
		btnCancel.setPreferredSize(btnAdd.getPreferredSize());
		miModify.setMnemonic('M');
		miModify.setText(miModify.getText() + "(M)");
		miDelete.setMnemonic('D');
		miDelete.setText(miDelete.getText() + "(D)");

		this.popup.add(miModify);
		this.popup.add(miDelete);
		buttonPane.add(btnModify, "End");
		buttonPane.add(btnDelete, "End");
		buttonPane.add(btnAdd, "End");
		buttonPane.add(btnCancel, "End");
		this.content.add(buttonPane, "South");
		this.content.add(scTable, "Center");
		setDefaultCloseOperation(2);
		pack();
		setResizable(false);
		setLocationRelativeTo(getOwner());
		UIUtil.escAndEnterAction(this, btnModify, this.cancelAction);

		this.table.getSelectionModel().addListSelectionListener(
				new ListSelectionListener() {
					public void valueChanged(ListSelectionEvent e) {
						UserListDialog.this.whenSelectionChanged(e);
					}
				});
		this.table.addMouseListener(new MouseAdapter() {
			@Override
			public void mousePressed(MouseEvent e) {
				UserListDialog.this.select(e);
			}

			@Override
			public void mouseReleased(MouseEvent e) {
				UserListDialog.this.showPopupMenu(e);
			}
		});
	}

	private void load() {
		List<User> list = UserDAO.getUsers(new Criterion[0]);
		this.model.delAllRow();
		this.userList.addAll(list);
		this.model.refreshUI();
	}

	private void whenSelectionChanged(ListSelectionEvent e) {
		this.currentUser = (this.table.getSelectedRow() < 0 ? null : this.model
				.getSelectedRowData());
		boolean selectedEmpty = this.currentUser == null;
		this.modifyAction.setEnabled(!selectedEmpty);
		this.deleteAction.setEnabled((!selectedEmpty)
				&& (this.currentUser.getPurview() > 0));
	}

	private void select(MouseEvent e) {
		int row = this.table.rowAtPoint(e.getPoint());

		if ((row >= 0) && (SwingUtilities.isRightMouseButton(e))) {
			this.table.getSelectionModel().setSelectionInterval(row, row);
		} else if ((row < 0) && (!SwingUtilities.isMiddleMouseButton(e))) {
			this.table.clearSelection();
		}
	}

	private void showPopupMenu(MouseEvent e) {
		int row = this.table.rowAtPoint(e.getPoint());

		if ((row >= 0) && (SwingUtilities.isRightMouseButton(e))) {
			this.popup.show((Component) e.getSource(), e.getX(), e.getY());
		}
	}
}